<?php

namespace App\Admin\Controllers;

use App\Http\Requests\CommentRequest;
use App\Http\Resources\CommentDetailResource;
use App\Models\Comment;
use Encore\Admin\Http\Controllers\AdminController;
use App\Models\Topic;
use App\Repositories\CommentRepository;
use App\Rules\TuWenContent;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Table;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CommentController extends AdminController
{
    protected $title = "回复";
    /**
     * Make a grid builder.
     *
     * @return Table
     */
    protected function table()
    {
        $table = new Table(new Comment);
        $tid = request('tid');
        $uid = request('uid');
        $table->model()->with(['user', 'topic', 'topic.forum', 'detail'])
        ->when($tid, function ($query) use ($tid) {
            return $query->where('tid', $tid);
        })->when($uid, function ($query) use ($uid) {
            return $query->where('uid', $uid);
        })->orderBy('id', 'desc');

        $table->id('Id');
        $table->column('detail','内容')->display(function () {
            $resource = new CommentDetailResource($this->detial);
            $content = $resource->normalizeContent($this->detail->content, true);
            return sprintf('<a href="%s" target="_blank">%s</a>', route('admin.comment.find', [$this->id]), $content);
        });
        $table->column('user.name', '作者')->display(function () {
            return sprintf('<a href="%s">%s</a>', route('admin.comment.index', ['uid' => $this->uid]), $this->user->name);
        });
        $table->column('topic.title', '帖子')->display(function () {
            return sprintf('<a href="%s">%s</a>', route('admin.comment.index', ['tid' => $this->tid]), optional($this->topic)->title);
        });
        $table->column('topic.forum.name', '版块')->display(function () {
            if ($this->topic && $this->topic->forum) {
                return $this->topic->forum->name;
            }
        });
        $table->floor_num('楼层');
        $table->comment_count('回复数');
        $table->created_at('发表时间');

//        dd($table->applyFilter(false));

        return $table;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Comment::findOrFail($id));

        $show->id('Id');
        $show->key('Key');
        $show->uid('Uid');
        $show->tid('Tid');
        $show->pid('Pid');
        $show->root_id('Root id');
        $show->floor_num('Floor num');
        $show->comment_count('Comment count');
        $show->like_count('Like count');
        $show->dislike_count('Dislike count');
        $show->favor_count('Favor count');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($topicOrComment = null)
    {
        $form = new Form(new Comment);
        if ($topicOrComment instanceof Topic) {
            $form->hidden('topic_key')->default($topicOrComment->key);
            $form->hidden('__redirect')->default(route('admin.topic.show', [$topicOrComment->id]));
        } elseif ($topicOrComment instanceof Comment) {
            $form->hidden('__redirect')->default(route('admin.topic.show', [$topicOrComment->tid]));
        }

        $form->content('content_detail', '回复内容')->rules(['required', new TuWenContent()]);

        $form->editing(function ($form) {
            $model = $form->model();
            $comment = $model;
            $detail = $comment->detail;
            $model->content_detail = json_encode($detail->content);

//            $hide = $comment->hide;
//            if ($hide) {
//                $model->content_hide = json_encode($hide->content);
//                $model->has_hide = 1;
//                $model->require_reply = $hide->require_reply;
//                $model->require_score = $hide->require_score;
//            }

//            $model->forum_key = $model->forum->key;
        });

        return $form;
    }

    public function store()
    {
        $request = request();
        $commentRepository = new CommentRepository();

        $result = $commentRepository->create($request);
        if ($request->wantsJson()) {
            return $result;
        } else {
            if ($request->__redirect) {
                return redirect($request->__redirect);
            } else {
                return back();
            }
        }

    }

    public function update($id)
    {
        $request = request();
        if ($validationMessages = $this->form()->validationMessages($request->all())) {
            return back()->withInput()->withErrors($validationMessages);
        }
        $commentRepository = new CommentRepository();

        $result = $commentRepository->update($request, $id);

        if ($request->__redirect) {
            return redirect($request->__redirect);
        } else {
            return back();
        }
    }

    /**
     * 楼中楼数据
     *
     * @param Request $request
     * @return array
     * @throws \Throwable
     */
    public function comment(Request $request)
    {
        $page = $request->page ?? 1;
        $rootComment = Comment::query()->findOrFail($request->root_id);
        $query = Comment::query()->with(['user', 'detail', 'parentComment', 'parentComment.user'])->orderBy('id', 'asc');
        if ($request->tid) {
            $query->where('tid', $request->tid);
        }
        if ($request->root_id) {
            $query->where('root_id', $request->root_id);
        }
        $list = $query->forPage($page, Topic::DETAIL_COMMENT_COMMENT_PAGE_SIZE)->get();

        $view = view('admin.topic.comment_comment', compact('list', 'rootComment', 'page'));
        return normalize(0, 'OK', ['html' => $view->render()]);
    }

    public function find($id)
    {
        $comment = Comment::query()->findOrFail($id);
        $tid = $comment->tid;
        if ($comment->floor_num == 1) {
            //直接跳到详情页
            return redirect()->route('admin.topic.show', [$tid]);
        }
        if ($comment->pid == 0) {
            //正常楼层，跳到那一页去
            $page = ceil($comment->floor_num / Topic::DETAIL_COMMENT_PAGE_SIZE);
            return redirect()->route('admin.topic.show', [$tid, 'page' => $page])->withFragment('#comment-' . $comment->id);
        }

        //最后是楼中楼。定位到根评论，其本身靠前端拉
        $parentComment = Comment::query()->findOrFail($comment->root_id);
        $page = ceil($parentComment->floor_num / Topic::DETAIL_COMMENT_PAGE_SIZE);
        $params = [
            $tid,
            'page' => $page,
        ];
        return redirect()->route('admin.topic.show', $params)->withFragment('#comment-' . $parentComment->id);
    }

    public function destroy($id)
    {
        $result = (new CommentRepository())->destroy($id);

        return $result;

    }

    public function restore($id)
    {
        $result = (new CommentRepository())->restore($id);

        return $result;

    }

}
